package tk.hongbo.rainbow.core;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.SoundPool;

public final class SoundPlayer {
    private SoundPool mSoundPool;

    private SoundPlayer() {
        AudioAttributes abs = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build();
        mSoundPool = new SoundPool.Builder()
                .setMaxStreams(100)   //设置允许同时播放的流的最大值
                .setAudioAttributes(abs)   //完全可以设置为null
                .build();
    }

    public static SoundPlayer getInstance() {
        return Holder.PLAYER;
    }

    public void play(Context context, int resourceId) {
        int id = mSoundPool.load(context, resourceId, 1);
        mSoundPool.setOnLoadCompleteListener((soundPool, sampleId, status) -> {
            if (sampleId == id) {
                mSoundPool.play(id, 1, 1, 1, 0, 1f);
            }
        });
    }

    public void release() {
        if (mSoundPool != null) {
            mSoundPool.release();
        }
        mSoundPool = null;
    }

    private static class Holder {
        private static final SoundPlayer PLAYER = new SoundPlayer();
    }

}
